package com.threaddemo5;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

public class ForkJoinRecurisiveAction {
    //最大计算数
    private static final int MAX_THRESHOLD = 5;

    private static int sum = 0;

    public static void main(String[] args) throws InterruptedException {
        //创建ForkJoinPool
        ForkJoinPool pool = new ForkJoinPool();
        //异步提交RecursiveAction任务
        pool.submit(new CalculatedRecurisiveTask(0,1000));
        //等待3秒后输出结果，因为计算需要时间
        pool.awaitTermination(3, TimeUnit.SECONDS);
        System.out.println("结果为："+sum);
    }

    private static class CalculatedRecurisiveTask extends RecursiveAction{
        private int start;
        private int end;
        public CalculatedRecurisiveTask(int start, int end) {
            this.start = start;
            this.end = end;
        }
        @Override
        protected void compute() {
            //判断计算范围，如果小于等于5，那么一个线程计算就够了，否则进行分割
            if ((end-start)<=5) {
                //因为没有返回值，所有这里如果我们要获取结果，需要存入公共的变量中

                synchronized (ForkJoinRecurisiveTask.class){
                    for (long i = start; i <= end; i++) {
                        sum += i;
                    }
                }
            }else {
                //任务分割
                int middle = (end+start)/2;
                CalculatedRecurisiveTask left = new CalculatedRecurisiveTask(start,middle);
                CalculatedRecurisiveTask right = new CalculatedRecurisiveTask(middle+1,end);
                //执行
                left.fork();
                right.fork();
            }
        }
    }
}


